'''Wrapper for RESTful api https://sm.ms/api'''

import pyautogui
import clipboard
import json
import os
from time import sleep
from git import Repo

def git_push(c):
    path = r'D:\StudyProject\BlogProject\GiteeShare\share'
    repo = Repo(path)
    git = repo.git
    git.add('.')
    git.commit('-m', c)
    git.push("origin", "master")


FLAG = 0

def pos():
    while True:
        print(pyautogui.position())

def upload(file_path, mode=0):
    global FLAG
    if not (os.path.exists(file_path) and os.path.isfile(file_path)):
            print("请见检查文件！")
    pyautogui.hotkey('alt', 'space')
    clipboard.copy(file_path)
    pyautogui.hotkey('ctrl', 'v')
    pyautogui.click(x=878, y=277)
    file_size = os.stat(file_path).st_size / (1024 * 1024)
    if mode==1:
        bed = 'AFDian'
    else:
        if  file_size > 9.8:
            bed = 'ImgBB'
        elif file_size > 4.8:
            bed = 'MeiTuan'
        elif file_size > 1.8:
            bed = 'JD'
        else:
            bed = 'BiuBiu'
    bed_url = "https://img.kinh.cc/?Type=" + bed
    if FLAG == 0:
        pyautogui.click(x=428, y=1066)
        FLAG = 1
    pyautogui.click(x=1033, y=60)
    pyautogui.hotkey('ctrl', 'a')
    pyautogui.write(bed_url)
    pyautogui.press('enter')
    pyautogui.press('enter')
    pyautogui.click(x=200, y=574)
    sleep(2)
    pyautogui.hotkey('ctrl', 'v')
    y = 780
    no_click = 0
    no_scroll = 0
    pyautogui.click(x=200, y=574)
    sgn = 1
    while not pyautogui.pixelMatchesColor(960, y,(48, 133, 214)):
        y = y+5
        if no_scroll==0 and y % 100 == 0:
            pyautogui.move(sgn*400, sgn*40)
            sgn = sgn*-1
        if y> 1000:
            y = 780
        if no_scroll==0:
            pyautogui.scroll(-50)
        if pyautogui.position().x < 100:
            no_scroll = 1
        if pyautogui.position().x > 1860:
            break
            no_click = 1
    if no_click == 0:
        pyautogui.click(x=960, y=y)
    return clipboard.paste()

def get_dir_info(dir_path, deep=0, info=None):
    if info is None:
        info = {'deep': 0, 'deep_dir': '', 'file_num': 0, 'dir_num': 0}
    if deep > info['deep']:
        info['deep'] = deep
        info['deep_dir'] = dir_path
    file_list = os.listdir(dir_path)
    for file in file_list:
        file_path = os.path.join(dir_path, file)
        if os.path.isdir(file_path):
            info['dir_num'] += 1
            get_dir_info(file_path, deep=deep+1, info=info)
        else:
            info['file_num'] += 1
    if deep == 0:
        return info

def get_file_list(path, path_index):
    gitee_url1 = 'https://gitee.com/giteehyj/share/raw/master/hiker/source/我的图集/'
    gitee_url2 = 'D:\\StudyProject\\BlogProject\\GiteeShare\\share\\hiker\\source\\我的图集\\'

    category = os.listdir(path)
    category = [c for c in category if os.path.isdir(os.path.join(path,c))]

    index_j = []

    now_file_num = 0
    now_file_num_0 = 0
    now_file_num_1 = 0
    now_file_num_2 = 0
    all_file_num = get_dir_info(path)['file_num']
    
    for c in category:
        json_file = os.path.join(path_index, c+'.json')
        if os.path.exists(json_file):
            with open(json_file, 'r') as f:
                data = f.read()
                if len(data) != 0:
                    dic_init = json.loads(data)
                else:
                    dic_init = []
        else:
            dic_init = []

        index_dic = {}
        index_dic['title'] = c
        index_dic['url'] = os.path.join(path_index,c+'.json').replace('.\\',gitee_url1).replace('\\', '/')
        index_j.append(index_dic)

        p = os.path.join(path, c)
        titles = os.listdir(p)

        j = []
        j_temp = []
        for t in titles:
            dic = {}
            dic_temp = {}
            dic['title'] = t
            dic_temp['title'] = t
            urls = []
            for n in os.listdir(os.path.join(p,t)):
                url1 = os.path.join(p,t,n).replace('\\', '/')
                exists_flag = 0
                exists_flag2 = 0
                for d in dic_init:
                    if t == d['title']:
                        for u in d['urls']:
                            if (u[0] == url1 and u[1] != '' and 'sogoucdn.com' not in u[1]):
                                exists_flag = 1
                                url2 = u[1]
                            if (u[0] == url1 and len(u)>2 and u[2] != ''):
                                exists_flag2 = 1
                                url3 = u[2]
                if exists_flag==0:
                    print(os.path.join(p,t,n))
                    # input()
                    url2 = upload(os.path.join(p,t,n), 1)
                    now_file_num_1 += 1 
                    print('now_file_num_1: {:4}'.format(now_file_num_1))
                if exists_flag2==0:
                    print(os.path.join(p,t,n))
                    # input()
                    url3 = upload(os.path.join(p,t,n))
                    now_file_num_2 += 1 
                    print('now_file_num_2: {:4}'.format(now_file_num_2))
                if exists_flag==0 and exists_flag2==0:
                    now_file_num_0 += 1 
                    print('all_file_num: {:4}'.format(now_file_num_0))
                urls.append([url1, url2, url3])
                now_file_num += 1
                print('{:4} / {:4}'.format(now_file_num, all_file_num))
                '''
                dic_temp['urls'] = urls
                j_temp.append(dic_temp)
                with open(os.path.join(path_index, c+'_temp.json'), 'w') as f:
                    f.write(json.dumps(j_temp))
                    '''
            dic['urls'] = urls
            j.append(dic)
        with open(os.path.join(path_index, c+'.json'), 'w') as f:
            f.write(json.dumps(j))
        
    with open(os.path.join(path_index, 'index.json'), 'w') as f:
        f.write(json.dumps(index_j))


if __name__ == '__main__':
    input("回车开始")
    # file_path = r'.\img_test'
    # url = upload(file_path)
    get_file_list(r'D:\StudyProject\BlogProject\GiteeShare\img', r'.\index')

    # d = get_dir_info(file_path)
    # print(d)

    flag = input("更新完成，是否提交到远程仓库（y/n）")
    if flag!='n':
        git_push("update 我的图集")
        input("提交完成！")
    else:
        input("运行完毕，未提交远程仓库")

    
    
    


